import React, { useState, useEffect, useRef } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Select, Button, Table, Space, message, Tag, Modal, Drawer, Input, Form } from 'antd';
import { ProCard, ProForm, ProFormText, ProFormSelect, ProFormDateRangePicker } from '@ant-design/pro-components';
import { 
  BugOutlined, 
  InfoCircleOutlined, 
  ExclamationCircleOutlined, 
  DownloadOutlined,
  ReloadOutlined,
  EyeOutlined,
  DeleteOutlined,
  SearchOutlined,
  WarningOutlined,
  CloseCircleOutlined 
} from '@ant-design/icons';
import { EchartsLine, EchartsColumn, EchartsPie } from '@/components/Charts';
import dayjs from 'dayjs';
import { 
  getSystemLogList, 
  getSystemLogDetail, 
  getSystemLogStatistics,
  exportSystemLogs,
  cleanupSystemLogs,
  getSystemLogCategoryDistribution 
} from '@/services/logsApi';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

const SystemLogs: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [statisticsLoading, setStatisticsLoading] = useState(false);
  const [logs, setLogs] = useState<LOGS.SystemLogModel[]>([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 });
  const [statistics, setStatistics] = useState<any>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [cleanupVisible, setCleanupVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState<LOGS.SystemLogModel | null>(null);
  const [searchParams, setSearchParams] = useState<LOGS.SystemLogListParams>({});
  const actionRef = useRef<any>();

  // 获取系统日志列表
  const fetchLogs = async (params: LOGS.SystemLogListParams = {}) => {
    setLoading(true);
    try {
      const response = await getSystemLogList({
        page: pagination.current,
        limit: pagination.pageSize,
        ...searchParams,
        ...params,
      });
      
      if (response.code === 200) {
        setLogs(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.pagination.total,
        }));
      } else {
        message.error(response.message || '获取系统日志失败');
      }
    } catch (error) {
      console.error('获取系统日志失败:', error);
      message.error('获取系统日志失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStatistics = async () => {
    setStatisticsLoading(true);
    try {
      const [statsResponse, categoryResponse] = await Promise.all([
        getSystemLogStatistics({
          start_date: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
          end_date: dayjs().format('YYYY-MM-DD'),
        }),
        getSystemLogCategoryDistribution({
          start_date: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
          end_date: dayjs().format('YYYY-MM-DD'),
        })
      ]);
      
      if (statsResponse.code === 200 && categoryResponse.code === 200) {
        setStatistics({
          ...statsResponse.data,
          category_distribution: categoryResponse.data,
        });
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setStatisticsLoading(false);
    }
  };

  // 查看日志详情
  const handleViewDetail = async (record: LOGS.SystemLogModel) => {
    try {
      const response = await getSystemLogDetail(record.id);
      if (response.code === 200) {
        setSelectedLog(response.data);
        setDetailVisible(true);
      } else {
        message.error(response.message || '获取日志详情失败');
      }
    } catch (error) {
      console.error('获取日志详情失败:', error);
      message.error('获取日志详情失败');
    }
  };

  // 导出日志
  const handleExport = async (format: 'excel' | 'csv' | 'json') => {
    try {
      await exportSystemLogs({
        log_type: 'system',
        format,
        start_date: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
        end_date: dayjs().format('YYYY-MM-DD'),
        filters: searchParams,
        include_details: true,
      });
      message.success(`${format.toUpperCase()}文件导出成功`);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  // 清理日志
  const handleCleanup = async (values: { retention_days: number; dry_run: boolean }) => {
    try {
      const response = await cleanupSystemLogs({
        log_type: 'system',
        retention_days: values.retention_days,
        dry_run: values.dry_run,
      });
      
      if (response.code === 200) {
        message.success(`${values.dry_run ? '预计' : '实际'}清理了 ${response.data.deleted_count} 条日志`);
        if (!values.dry_run) {
          setCleanupVisible(false);
          fetchLogs();
          fetchStatistics();
        }
      } else {
        message.error(response.message || '清理失败');
      }
    } catch (error) {
      console.error('清理失败:', error);
      message.error('清理失败');
    }
  };

  useEffect(() => {
    fetchLogs();
    fetchStatistics();
  }, []);

  // 日志级别颜色映射
  const getLevelColor = (level: string) => {
    const colorMap: Record<string, string> = {
      debug: 'default',
      info: 'blue',
      warn: 'orange',
      error: 'red',
      fatal: 'magenta',
    };
    return colorMap[level] || 'default';
  };

  // 日志级别图标映射
  const getLevelIcon = (level: string) => {
    const iconMap: Record<string, React.ReactNode> = {
      debug: <BugOutlined />,
      info: <InfoCircleOutlined />,
      warn: <WarningOutlined />,
      error: <ExclamationCircleOutlined />,
      fatal: <CloseCircleOutlined />,
    };
    return iconMap[level] || <InfoCircleOutlined />;
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      sorter: true,
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      render: (level: string) => (
        <Tag color={getLevelColor(level)} icon={getLevelIcon(level)}>
          {level.toUpperCase()}
        </Tag>
      ),
      filters: [
        { text: 'DEBUG', value: 'debug' },
        { text: 'INFO', value: 'info' },
        { text: 'WARN', value: 'warn' },
        { text: 'ERROR', value: 'error' },
        { text: 'FATAL', value: 'fatal' },
      ],
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      ellipsis: true,
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
      width: 300,
      ellipsis: true,
    },
    {
      title: '追踪ID',
      dataIndex: 'trace_id',
      key: 'trace_id',
      width: 120,
      ellipsis: true,
      render: (traceId: string) => traceId ? (
        <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
          {traceId}
        </span>
      ) : '-',
    },
    {
      title: '用户ID',
      dataIndex: 'user_id',
      key: 'user_id',
      width: 100,
      render: (userId: number) => userId || '-',
    },
    {
      title: 'IP地址',
      dataIndex: 'ip_address',
      key: 'ip_address',
      width: 120,
      render: (ip: string) => ip || '-',
    },
    {
      title: '响应状态',
      dataIndex: 'response_status',
      key: 'response_status',
      width: 100,
      render: (status: number) => status ? (
        <Tag color={status >= 200 && status < 300 ? 'green' : status >= 400 ? 'red' : 'orange'}>
          {status}
        </Tag>
      ) : '-',
    },
    {
      title: '执行时间',
      dataIndex: 'execution_time',
      key: 'execution_time',
      width: 100,
      render: (time: number) => time ? `${time}ms` : '-',
    },
    {
      title: '内存使用',
      dataIndex: 'memory_usage',
      key: 'memory_usage',
      width: 100,
      render: (memory: number) => memory ? `${(memory / 1024 / 1024).toFixed(1)}MB` : '-',
    },
    {
      title: '记录时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
      sorter: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      fixed: 'right' as const,
      render: (record: LOGS.SystemLogModel) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和操作栏 */}
      <ProCard
        title="系统日志"
        extra={
          <Space>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => {
                fetchLogs();
                fetchStatistics();
              }}
              loading={loading}
            >
              刷新
            </Button>
            <Button.Group>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('excel')}
              >
                导出Excel
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('csv')}
              >
                导出CSV
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('json')}
              >
                导出JSON
              </Button>
            </Button.Group>
            <Button
              icon={<DeleteOutlined />}
              onClick={() => setCleanupVisible(true)}
              danger
            >
              清理日志
            </Button>
          </Space>
        }
        style={{ marginBottom: 24 }}
      />

      {/* 统计概览 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="总日志数"
              value={statistics?.system_logs?.total_count || 0}
              prefix={<InfoCircleOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="今日日志"
              value={statistics?.system_logs?.today_count || 0}
              prefix={<InfoCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="平均响应时间"
              value={statistics?.system_logs?.performance_metrics?.average_response_time || 0}
              suffix="ms"
              prefix={<ExclamationCircleOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="平均内存使用"
              value={(statistics?.system_logs?.performance_metrics?.average_memory_usage || 0) / 1024 / 1024}
              precision={1}
              suffix="MB"
              prefix={<WarningOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 统计图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="日志级别分布" loading={statisticsLoading}>
            <EchartsPie
              data={statistics?.system_logs?.level_distribution || []}
              angleField="count"
              colorField="level"
              radius={0.8}
              label={{
                type: 'outer',
                content: '{name}: {percentage}',
              }}
              height={250}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="日志分类分布" loading={statisticsLoading}>
            <EchartsColumn
              data={statistics?.category_distribution || []}
              xField="category"
              yField="count"
              color="#52c41a"
              columnWidthRatio={0.8}
              meta={{
                category: { alias: '分类' },
                count: { alias: '日志数量' },
              }}
              height={250}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="性能指标趋势" loading={statisticsLoading}>
            <EchartsLine
              data={[
                { type: '响应时间', value: statistics?.system_logs?.performance_metrics?.average_response_time || 0 },
                { type: '内存使用', value: (statistics?.system_logs?.performance_metrics?.average_memory_usage || 0) / 1024 },
                { type: 'CPU使用', value: statistics?.system_logs?.performance_metrics?.average_cpu_usage || 0 },
              ]}
              xField="type"
              yField="value"
              smooth={true}
              color="#1890ff"
              point={{
                size: 5,
                shape: 'circle',
              }}
              height={250}
            />
          </ProCard>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <ProCard style={{ marginBottom: 24 }}>
        <ProForm
          layout="horizontal"
          submitter={{
            render: (props, doms) => (
              <Row>
                <Col span={14} offset={5}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      onClick={() => {
                        props.form?.validateFields().then((values) => {
                          const params = {
                            ...values,
                            start_date: values.dateRange?.[0]?.format('YYYY-MM-DD'),
                            end_date: values.dateRange?.[1]?.format('YYYY-MM-DD'),
                          };
                          delete params.dateRange;
                          setSearchParams(params);
                          setPagination(prev => ({ ...prev, current: 1 }));
                          fetchLogs(params);
                        });
                      }}
                    >
                      搜索
                    </Button>
                    <Button
                      onClick={() => {
                        props.form?.resetFields();
                        setSearchParams({});
                        setPagination(prev => ({ ...prev, current: 1 }));
                        fetchLogs({});
                      }}
                    >
                      重置
                    </Button>
                  </Space>
                </Col>
              </Row>
            ),
          }}
        >
          <Row gutter={16}>
            <Col span={6}>
              <ProFormSelect
                name="level"
                label="日志级别"
                placeholder="请选择日志级别"
                options={[
                  { label: 'DEBUG', value: 'debug' },
                  { label: 'INFO', value: 'info' },
                  { label: 'WARN', value: 'warn' },
                  { label: 'ERROR', value: 'error' },
                  { label: 'FATAL', value: 'fatal' },
                ]}
              />
            </Col>
            <Col span={6}>
              <ProFormText
                name="category"
                label="分类"
                placeholder="请输入分类名称"
              />
            </Col>
            <Col span={6}>
              <ProFormText
                name="trace_id"
                label="追踪ID"
                placeholder="请输入追踪ID"
              />
            </Col>
            <Col span={6}>
              <ProFormDateRangePicker
                name="dateRange"
                label="记录时间"
                placeholder={['开始时间', '结束时间']}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <ProFormText
                name="user_id"
                label="用户ID"
                placeholder="请输入用户ID"
              />
            </Col>
            <Col span={6}>
              <ProFormText
                name="ip_address"
                label="IP地址"
                placeholder="请输入IP地址"
              />
            </Col>
            <Col span={6}>
              <ProFormText
                name="keyword"
                label="关键词"
                placeholder="搜索消息内容"
              />
            </Col>
          </Row>
        </ProForm>
      </ProCard>

      {/* 系统日志表格 */}
      <ProCard>
        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 20 }));
              fetchLogs({ page, limit: pageSize });
            },
          }}
          scroll={{ x: 1600 }}
          size="small"
        />
      </ProCard>
    </div>
  );
};

export default SystemLogs;
